import { Breadcrumb, Button, Table, Space, Modal, Flex, TableProps, message } from 'antd';
import React, { FC } from 'react';
import { FormPanel, type FormPanelObject, InputType, Utils, StandUploadExcel } from 'lfun-bg-comp';
import { useNavigate } from 'react-router-dom';
import _ from 'lodash';
import { PageContainer } from '@/component/page-container';
import { GENDER } from '@/constant/basicOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import CreateForm from './create';
import OutForm from './out';
import { ID_TYPE, STUDENT_APPROVALATATUS } from '@/constant/studentOptions';
import { getPathRoot } from '@/utils';
import { StuNewStudentSrv } from '@/service/student/newStudent';
import { TNewStudents } from '@/service/student/types';
import {
  searchSchoolOptions,
  getClassesOptionsBySchool,
  getGradesOptionsBySchool,
  getProvinceCityCascader,
} from '@/service/options';
import { IMPORT_EXCEL_TEMPLATE } from '@/constant';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import useCountry from '@/hooks/useCountry';

const Groups: FC = () => {
  const navigate = useNavigate();
  const [value, setValue] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(10);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [loading, setLoading] = React.useState(false);
  const country = useCountry();

  // 去入学表分页
  const [rsTotal, setRsTotal] = React.useState(0);
  const [rsPageSize, setRsPageSize] = React.useState(10);
  const [rsPageIndex, setRsPageIndex] = React.useState(1);
  const [rsloading, setRsLoading] = React.useState(false);
  const [curFormPanelObject, setCurFormPanelObject] = React.useState<any>();
  const [cur, setCur] = React.useState<any>();
  const isSchool = Utils.getProps('isSchool');
  const searchFunc = async (params, pageIndex, pageSize) => {
    setLoading(true);
    const param: TNewStudents.TReqNewStudentsParams = {
      ...params,
      page: pageIndex,
      per_page: pageSize,
    };
    if (params.enrollment_date) {
      param.enrollment_date = params.enrollment_date.format('YYYY-MM-DD');
    }
    const r = await StuNewStudentSrv.list(param);
    if (r.success) {
      setValue(r?.data?.items || []);
      setTotal(r?.data?.total || 0);
      setPageIndex(pageIndex);
      setPageSize(pageSize);
    } else if (curFormPanelObject) {
      curFormPanelObject.reVaildation(r);
    }
    setLoading(false);
  };

  React.useEffect(() => {
    searchFunc({}, pageIndex, pageSize);
  }, []);

  const pageChange = (pageIndex, pageSize) => {
    searchFunc(curFormPanelObject.getFieldsValue(), pageIndex, pageSize);
  };

  const rspageChange = async (pageIndex, pageSize, callback?) => {
    setRsLoading(true);
    const param: TNewStudents.TReqNewStudentsParams = {
      ...{ approval_status: 'enrollment' },
      page: pageIndex,
      per_page: pageSize,
    };
    const r = await StuNewStudentSrv.list(param);
    if (r.success) {
      if (callback && callback(r.data.total)) {
        setRsLoading(false);
        return;
      }
      setRsPageIndex(pageIndex);
      setRsPageSize(pageSize);
      setNonAssignment(r?.data?.items || []);
      setRsTotal(r?.data?.total || 0);
    } else if (curFormPanelObject) {
      curFormPanelObject.reVaildation(r);
    }
    setRsLoading(false);
  };

  function handleView(route, record) {
    navigate(`${getPathRoot()}/newstudent/${route}/${record.student_id}`, { state: { ...record } });
  }

  function handleDelete(record) {
    setCur(record);
    setShowDelModel(true);
  }

  function handleOutFlow(record) {
    //console.log('流出', record);
    setCur(record);
    setShowOutModel(true);
  }

  const columns: TableProps['columns'] = [
    {
      title: '姓名',
      dataIndex: 'student_name',
      key: 'student_name',
      width: 100,
      fixed: 'left',
    },
    {
      title: '证件类型',
      dataIndex: 'id_type',
      key: 'id_type',
      render(v) {
        return _.find(ID_TYPE, { value: v })?.label;
      },
    },
    {
      title: '证件号码',
      dataIndex: 'id_number',
      key: 'id_number',
      width: 200,
    },
    {
      title: '普查号',
      dataIndex: 'enrollment_number',
      key: 'enrollment_number',
    },
    {
      title: '性别',
      dataIndex: 'student_gender',
      key: 'student_gender',
      width: 100,
      render(v) {
        return _.find(GENDER, { value: v })?.label;
      },
    },
    {
      title: '状态',
      dataIndex: 'approval_status',
      key: 'approval_status',
      render(v) {
        return _.find(STUDENT_APPROVALATATUS, { value: v })?.label;
      },
    },
    {
      title: '年级',
      dataIndex: 'grade_name',
      key: 'grade_name',
    },
    {
      title: '班级',
      dataIndex: 'class_name',
      key: 'class_name',
    },
    {
      title: '区县',
      dataIndex: 'block',
      key: 'block',
      render: (text: any) => {
        return _.find(country, { value: String(text) })?.label;
      },
    },
    {
      title: '学校名称',
      dataIndex: 'school_name',
      key: 'school_name',
    },
    {
      title: '操作',
      key: 'actions',
      fixed: 'right',
      //width: 300,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          <PermissionButton permission="view">
            <Button type="link" onClick={() => handleView('details', record)}>
              查看
            </Button>
          </PermissionButton>
          {isSchool ? (
            <>
              {record.approval_status === 'enrollment' && (
                <PermissionButton permission="edit">
                  <Button type="link" onClick={() => handleView('edit', record)}>
                    编辑
                  </Button>
                </PermissionButton>
              )}
              <PermissionButton permission="delete_student_keyinfo">
                <Button type="link" onClick={() => handleDelete(record)}>
                  删除
                </Button>
              </PermissionButton>
            </>
          ) : (
            <></>
          )}
          {Utils.getProps('isSchool') && record.approval_status === 'enrollment' && (
            <PermissionButton permission="flowout">
              <Button type="link" onClick={() => handleOutFlow(record)}>
                流出
              </Button>
            </PermissionButton>
          )}
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '普查号',
          name: 'enrollment_number',
          key: 'enrollment_number',
        },
        {
          label: '学校',
          name: 'school',
          key: 'school',
          relationFields: ['grade_id'],
          inputType: InputType.search, //'children',
          renderOption: searchSchoolOptions,
          formatSubmitValue: val => {
            if (typeof val === 'object') {
              return val.value;
            }
            return val;
          },
        },
        {
          label: '身份证件类型',
          name: 'id_type',
          key: 'id_type_0',
          inputType: InputType.select,
          renderOption: ID_TYPE,
        },
        {
          label: '姓名',
          name: 'student_name',
          key: 'student_name',
          textRange: [0, 20],
        },
        {
          label: '登记时间',
          name: 'enrollment_date',
          key: 'enrollment_date',
          inputType: InputType.date,
        },
        {
          label: '性别',
          name: 'student_gender',
          key: 'student_gender',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '状态',
          name: 'approval_status',
          key: 'approval_status',
          inputType: InputType.select,
          renderOption: STUDENT_APPROVALATATUS,
        },
        {
          label: '年级',
          name: 'grade_id',
          key: 'grade_id',
          relationFields: ['class_id'],
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) => {
            const res = await getGradesOptionsBySchool(form.getFieldsValue()?.school_id);
            return res;
          },
        },
        {
          label: '班级',
          name: 'class_id',
          key: 'class_id',
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) =>
            getClassesOptionsBySchool(form.getFieldsValue()?.school_id, form),
        },
      ],
    },
  ];

  const columnsSchool: TableProps['columns'] = [
    {
      title: '序号',
      dataIndex: 'student_id',
      key: 'student_id',
    },
    {
      title: '姓名',
      dataIndex: 'student_name',
      key: 'student_name',
    },
    {
      title: '年级',
      dataIndex: 'grade_name',
      key: 'grade_name',
    },
    {
      title: '班级',
      dataIndex: 'class_name',
      key: 'class_name',
    },
    {
      title: '普查号',
      dataIndex: 'enrollment_number',
      key: 'enrollment_number',
    },
    {
      title: '证件类型',
      dataIndex: 'id_type',
      key: 'id_type',
      render: v => {
        return _.find(ID_TYPE, { value: v })?.label;
      },
    },
    {
      title: '证件号码',
      dataIndex: 'id_number',
      key: 'id_number',
    },
    {
      title: '性别',
      dataIndex: 'student_gender',
      key: 'student_gender',
      render(v) {
        return _.find(GENDER, { value: v })?.label;
      },
    },
  ];
  const [nonAssignment, setNonAssignment] = React.useState([]);
  const [showCreateModel, setShowCreateModel] = React.useState(false);
  const [showDelModel, setShowDelModel] = React.useState(false);
  const [showSchoolModel, setShowSchoolModel] = React.useState(false);
  const [showOutModel, setShowOutModel] = React.useState(false);
  //const [showImportModel, setShowImportModel] = React.useState(false);

  return (
    <PageContainer header={<Breadcrumb items={[{ title: '新生入学管理' }]} />}>
      <FormPanel
        btnsAlign="right"
        restBtnText="重置"
        submitBtnText="查询"
        onLoad={(formPanelObject: FormPanelObject) => {
          setCurFormPanelObject(formPanelObject);
        }}
        onFinish={(formPanelObject: FormPanelObject) => {
          searchFunc(formPanelObject.getFieldsValue(), 1, pageSize);
        }}
        template={list}
      />
      <Flex gap="small" wrap="wrap" style={{ marginBottom: 20 }}>
        {Utils.getProps('isSchool') ? (
          <PermissionButton permission="open">
            <Button type="primary" onClick={() => setShowCreateModel(true)}>
              新生登记
            </Button>
          </PermissionButton>
        ) : (
          <></>
        )}
        {/* <Button onClick={() => setShowImportModel(true)}>新生导入</Button> */}
        {isSchool && (
          <>
            <PermissionButton permission="import">
              <StandUploadExcel
                uploadSrv="/school/v1/storage/school-upload-uri"
                templateUrl={IMPORT_EXCEL_TEMPLATE.new_student}
                templateName="资源导入模版.xlsx"
                showExcelSrv="/school/v1/storage/file-data-preview"
                scene="new_student"
                onImport={async (data, file_name, bucket_name) => {
                  const res = await StuNewStudentSrv.importNewStudent({
                    file_name,
                    bucket_name,
                    scene: 'new_student',
                  });
                  if (res.success) {
                    message.success('导入成功');
                    searchFunc({}, 1, pageSize);
                    return true;
                  } else {
                    message.error(res.message || res.details);
                    return false;
                  }
                }}
              >
                导入
              </StandUploadExcel>
            </PermissionButton>
            <PermissionButton permission="formaladmission">
              <Button
                type="primary"
                onClick={async () => {
                  rspageChange(1, pageSize, r => {
                    if (r > 0) setShowSchoolModel(true);
                    else message.info('无可正式入学学生');
                  });
                }}
              >
                正式入学
              </Button>
            </PermissionButton>
            <PermissionButton permission="sync">
              <Button type="primary">同步新生</Button>
            </PermissionButton>
          </>
        )}
      </Flex>
      <Table
        dataSource={value}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <CreateForm
        show={showCreateModel}
        onChange={hidden => {
          searchFunc({}, 1, pageSize);
          setShowCreateModel(hidden);
        }}
      />
      <OutForm value={cur} show={showOutModel} onChange={setShowOutModel} />
      <Modal
        title="删除"
        width="40%"
        open={showDelModel}
        onOk={async () => {
          const r = await StuNewStudentSrv.delete(cur.student_id);
          if (r.success) {
            searchFunc(curFormPanelObject.getFieldsValue(), pageIndex, pageSize);
            setShowDelModel(false);
            message.error('删除成功');
          } else {
            message.error('删除失败');
          }
        }}
        onCancel={() => setShowDelModel(false)}
      >
        {`新生${cur?.student_name}是否删除?`}
      </Modal>
      <Modal
        title="正式入学"
        width="60%"
        okText="正式入学"
        open={showSchoolModel}
        onOk={() => navigate(`${getPathRoot()}/newstudent/classroom`)}
        onCancel={() => setShowSchoolModel(false)}
      >
        <Table
          dataSource={nonAssignment}
          columns={columnsSchool}
          loading={rsloading}
          scroll={{ x: 'max-content' }}
          pagination={{
            ...PAGINATIONCONFIG,
            total: rsTotal,
            pageSize: rsPageSize,
            current: rsPageIndex,
            onChange: rspageChange,
          }}
        />
      </Modal>
    </PageContainer>
  );
};

export default Groups;
